#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/sem.h>
#include <sys/shm.h>

#define NLOOPS  1000
#define SIZE    sizeof(long)

static int update(long *ptr)
{
    return ((*ptr)++);
}

int main(int argc, char *argv[])
{
    int i, counter, shmid, semid;
    pid_t pid;
    void *area;
    struct sembuf buf1, buf2, buf3, buf4;


    if ((shmid = shmget(IPC_PRIVATE, SIZE, 0600)) < 0)
    {
        perror("shmget error");
        exit(0);
    }

    if ((area = shmat(shmid, NULL, 0)) == NULL)
    {
        perror("shmat error");
        exit(0);
    }

    if ((semid = semget(IPC_PRIVATE, 2, 0600)) < 0)
    {
        perror("semget error");
        exit(0);
    }

    if (semctl(semid, 0, SETVAL, 0) < 0)
    {
        perror("semctl set val error");
        exit(0);
    }

    if (semctl(semid, 1, SETVAL, 0) < 0)
    {
        perror("semctl set val error");
        exit(0);
    }

    buf1.sem_num = 0;
    buf1.sem_op = -1;
    buf1.sem_flg = SEM_UNDO;

    buf2.sem_num = 1;
    buf2.sem_op = -1;
    buf2.sem_flg = SEM_UNDO;

    buf3.sem_num = 0;
    buf3.sem_op = 1;
    buf3.sem_flg = 0;

    buf4.sem_num = 1;
    buf4.sem_op = 1;
    buf4.sem_flg = 0;

    if ((pid = fork()) == 0)
    {
        for (i = 1; i < NLOOPS+1; i+=2)
        {
            if (semop(semid, &buf1, 1) < 0)
            {
                perror("semop wait 0 error");
                exit(0);
            }

            if ((counter = update((long *)area)) != i)
            {
                fprintf(stderr, "child: expected %d, got %d\n", i, counter);
                exit(0);
            }
            else
                printf("c: %d\n", i);

            if (semop(semid, &buf4, 1) < 0)
            {
                perror("semop signal 1 error");
                exit(0);
            }
        }
    }
    else
    {
        for (i = 0; i < NLOOPS; i+=2)
        {
            if ((counter = update((long *)area)) != i)
            {
                fprintf(stderr, "parent: expected %d, got %d\n", i, counter);
                exit(0);
            }
            else
                printf("p: %d\n", i);

            if (semop(semid, &buf3, 1) < 0)
            {
                perror("semop signal 0 error");
                exit(0);
            }

            if (semop(semid, &buf2, 1) < 0)
            {
                perror("semop wait 1 error");
                exit(0);
            }
        }
    }

    return 0;
}
